import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';

/// 直接把数据传递给需要的小部件

class ScopedModelWidget extends StatelessWidget {
  const ScopedModelWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScopedModel<CountModel>(
      model: CountModel(),
      child: Scaffold(
        appBar: AppBar(
          title: Text("ScopedModel示例"),
        ),
        body: CounterWrapper(),
        floatingActionButton: ScopedModelDescendant<CountModel>(
          rebuildOnChange: false, // 不重新构建
          builder: (context, _, model) {
            return FloatingActionButton(
              onPressed: model.incrementCount,
              child: Icon(Icons.add),
            );
          },
        ),
      ),
    );
  }
}

/// 数据计数model
class CountModel extends Model {
  int count = 0;

  void incrementCount() {
    count++;
    // 通知变化 更新
    notifyListeners();
  }
}

class CounterWrapper extends StatelessWidget {
  CounterWrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: CounterWiget(),
    );
  }
}

class CounterWiget extends StatelessWidget {
  CounterWiget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<CountModel>(
      builder: (context, _, model) {
        return ActionChip(
          label: Text("${model.count}"),
          onPressed: model.incrementCount,
        );
      },
    );
  }
}
